package com.qyhl.webtv.module_microvideo.shortvideo.classic.detail;

import android.annotation.SuppressLint;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.avos.avoscloud.LogUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.flyco.tablayout.SlidingTabLayout;
import com.gyf.immersionbar.ImmersionBar;
import com.gyf.immersionbar.OnKeyboardListener;
import com.qyhl.webtv.basiclib.base.BaseActivity;
import com.qyhl.webtv.basiclib.base.BaseIViewPresenter;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.ARouterPathConstant;
import com.qyhl.webtv.commonlib.entity.microvideo.ClassicProgramBean;
import com.qyhl.webtv.commonlib.entity.microvideo.ClassicProgramNoticeBean;
import com.qyhl.webtv.commonlib.service.UserService;
import com.qyhl.webtv.commonlib.utils.MShareBoard;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;
import com.qyhl.webtv.commonlib.utils.router.RouterManager;
import com.qyhl.webtv.commonlib.utils.view.video.detailvideo.QYVideoPlayer;
import com.qyhl.webtv.module_microvideo.R;
import com.qyhl.webtv.module_microvideo.R2;
import com.qyhl.webtv.module_microvideo.shortvideo.classic.detail.comment.ClassicCommentFragment;
import com.qyhl.webtv.module_microvideo.shortvideo.classic.detail.introduction.ClassicIntroductionFragment;
import com.qyhl.webtv.module_microvideo.shortvideo.classic.detail.live.ClassicLiveFragment;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.weavey.loading.lib.LoadingLayout;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

@Route(path = ARouterPathConstant.CLASSIC_DETAIL_NEW)
public class ClassicDetailNewActivity extends BaseActivity implements ClassicDetailContract.ClassicDetailView {
    @BindView(R2.id.video_player)
    QYVideoPlayer videoPlayer;
    @BindView(R2.id.pro_title)
    TextView proTitle;
    @BindView(R2.id.hit_num)
    TextView hitNum;
    @BindView(R2.id.comment)
    EditText comment;
    @BindView(R2.id.bottom_layout)
    RelativeLayout bottomLayout;
    @BindView(R2.id.tab_layout)
    SlidingTabLayout tabLayout;
    @BindView(R2.id.viewPager)
    ViewPager viewPager;
    @BindView(R2.id.load_mask)
    LoadingLayout loadMask;
    @BindView(R2.id.follow_btn)
    ImageButton followBtn;
    @BindView(R2.id.title)
    TextView title;
    @BindView(R2.id.send_btn)
    TextView sendBtn;

    private String programId;

    private ClassicDetailPresenter mPresenter;

    private ClassicProgramBean mBean;

    private int index;

    private String titleName;

    private boolean isLive;

    private boolean isAuto;

    private int status;// 0 直播  1 预告  2 结束

    private int followNum;

    private MBadgeView badgeView;

    private ClassicProgramNoticeBean noticeBean;


    @Override
    protected int getContentView() {
        return R.layout.micro_activity_classic_detail_new;
    }

    @Override
    protected void setImmersionBar(ImmersionBar mImmersionBar) {
        mImmersionBar.setOnKeyboardListener(new OnKeyboardListener() {
            @Override
            public void onKeyboardChange(boolean isPopup, int keyboardHeight) {
                if (mBean != null && isPopup) {
                    index = 0;
                    if (mBean.getIsNotice() == 1) {
                        index++;
                    }

                    if (mBean.getIsDesc() == 1) {
                        index++;
                    }

                    if (mBean.getIsQuestions() == 1) {
                        index++;
                    }

                    switch (index) {
                        case 1:
                            tabLayout.setCurrentTab(0);
                            break;
                        case 2:
                            tabLayout.setCurrentTab(1);
                            break;
                        case 3:
                            tabLayout.setCurrentTab(2);
                            break;
                    }

                }
            }
        }).titleBar(R.id.title_layout).statusBarDarkFont(false).init();
    }

    @Override
    protected BaseIViewPresenter initBaseIViewPresenter() {
        return null;
    }

    @Override
    protected void init() {
        loadMask.setStatus(LoadingLayout.Loading);
        BusFactory.getBus().register(this);
        mPresenter = new ClassicDetailPresenter(this);

        programId = getIntent().getStringExtra("id");
        titleName = getIntent().getStringExtra("title");
        isLive = getIntent().getBooleanExtra("isLive", false);
        status = getIntent().getIntExtra("status", 0);
        isAuto = getIntent().getBooleanExtra("isAuto", true);
        switch (status) {
            case 0:
                break;
            case 1:
                showToast("节目尚未开始！");
                break;
            case 2:
                showToast("节目已结束！");
                break;
        }

        title.setText(titleName);

        mPresenter.getData(programId);
    }

    @Override
    protected void setListener() {
        loadMask.setOnReloadListener(new LoadingLayout.OnReloadListener() {
            @Override
            public void onReload(View v) {
                loadMask.setReloadButtonText("加载中...");
                mPresenter.getData(programId);
            }
        });

        //点赞
        followBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                followNum++;
                if (badgeView == null) {
                    badgeView = new MBadgeView(ClassicDetailNewActivity.this);
                }
                badgeView.bindTarget(followBtn).setBadgeNumber(followNum);
                mPresenter.doFollow(programId);
            }
        });
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void setData(ClassicProgramBean bean) {
        loadMask.setStatus(LoadingLayout.Success);
        loadMask.setReloadButtonText("点击重试~");
        mBean = bean;

        followNum = bean.getLove();

        if (badgeView == null) {
            badgeView = new MBadgeView(this);
        }
        badgeView.bindTarget(followBtn).setBadgeNumber(followNum);

        proTitle.setText(bean.getName());
        hitNum.setText(StringUtils.transformNum(bean.getHits() + "") + "人学习");

        List<String> nameList = new ArrayList<>();
        List<Fragment> fragments = new ArrayList<>();

        if (mBean.getIsNotice() == 1) {
            nameList.add("节目");
            fragments.add(ClassicLiveFragment.newInstance(mBean.getName(), mBean.getId() + "", isLive, status));
        }

        if (mBean.getIsQuestions() == 1) {
            comment.setVisibility(View.VISIBLE);
            sendBtn.setVisibility(View.VISIBLE);
            nameList.add("留言");
            fragments.add(ClassicCommentFragment.newInstance(mBean.getName(), mBean.getId() + ""));
        } else {
            comment.setVisibility(View.INVISIBLE);
            sendBtn.setVisibility(View.INVISIBLE);
        }

        if (mBean.getIsDesc() == 1) {
            nameList.add("嘉宾");
            fragments.add(ClassicIntroductionFragment.newInstance(mBean));
        }

        viewPager.setAdapter(new Adapter(this.getSupportFragmentManager(), fragments, nameList));
        tabLayout.setViewPager(viewPager);


        //设置封面图
        ImageView imageView = new ImageView(this);
        Glide.with(this.getApplicationContext())
                .load(mBean.getCover())
                .apply(new RequestOptions().centerCrop().error(R.drawable.cover_normal_default).placeholder(R.drawable.cover_normal_default))
                .into(imageView);
        videoPlayer.setThumbImageView(imageView);

        videoPlayer.setRotateViewAuto(false);
        videoPlayer.setLockLand(true);
        videoPlayer.setUp("", true, "");
        videoPlayer.getFullscreenButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
                videoPlayer.startWindowFullscreen(ClassicDetailNewActivity.this, true, true);
            }
        });

        if (videoPlayer.isIfCurrentIsFullscreen()) {
            videoPlayer.getBackButton().setVisibility(View.VISIBLE);
        } else {
            videoPlayer.getBackButton().setVisibility(View.GONE);
        }


        videoPlayer.getBackButton().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!GSYVideoManager.backFromWindowFull(ClassicDetailNewActivity.this)) {
                    finish();
                }
            }
        });


    }

    @Override
    public void setError(String msg) {

    }

    @Override
    public void commentSuccess(String msg) {
        dismissLoading();
        comment.setText("");
        showToast(msg);
    }

    @Override
    public void commentError(String msg) {
        dismissLoading();
        showToast(msg);
    }

    @Override
    public void followResult(String msg) {
        LogUtil.log.i(msg);
    }

    @OnClick({R2.id.share_btn, R2.id.send_btn, R2.id.back_btn})
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.share_btn) {
            if (noticeBean != null) {
                MShareBoard shareBoard = new MShareBoard(ClassicDetailNewActivity.this, programId, noticeBean.getTitle(), mBean.getCover(), noticeBean.getDesc(), 29, noticeBean.getId() + "", false);
                shareBoard.showPopupWindow();
            } else {
                MShareBoard shareBoard = new MShareBoard(ClassicDetailNewActivity.this, programId, titleName, mBean.getCover(), mBean.getDesc(), 29, "", false);
                shareBoard.showPopupWindow();
            }
        } else if (viewId == R.id.send_btn) {
            if (StringUtils.isNotEmpty(comment.getText().toString())) {
                CommonUtils.getInstance().isLogin(new UserService.LoginCallBack() {
                    @Override
                    public void login(boolean isLogin) {
                        if (isLogin) {
                            String phone = CommonUtils.getInstance().getUserName();
                            String name = CommonUtils.getInstance().getNickName();
                            showLoading();
                            mPresenter.doComment(name, phone, comment.getText().toString(), programId);
                            hideKeyboard(comment.getWindowToken());
                        } else {
                            RouterManager.routerLogin(ClassicDetailNewActivity.this, 0);
                            showToast("尚未登录或登录已失效！");
                        }

                    }

                    @Override
                    public void error(String s) {

                    }
                });
            } else {
                showToast("请输入您的提问！");
            }
        } else if (viewId == R.id.back_btn) {
            finish();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getEventMessage(Event.ClassicNotice event) {
        if (event != null) {
            noticeBean = event.getBean();

            if (videoPlayer == null) {
                return;
            }
            videoPlayer.setUp(noticeBean.getUrl() == null ? "" : noticeBean.getUrl(), false, "");

            if (noticeBean.getType().equals("LIVE")) {
                videoPlayer.setMode(QYVideoPlayer.PlayMode.LIVE);
                videoPlayer.hideStatusBtn(true);
                if (DateUtils.isDuringTime(noticeBean.getStartTime(), noticeBean.getEndTime())) {
                    if (isAuto) {
                        videoPlayer.getStartButton().performClick();//自动播放
                    }
                } else if (DateUtils.isBeforeTime(noticeBean.getStartTime())) {
                    //设置封面图
                    ImageView imageView = new ImageView(this);
                    imageView.setImageResource(R.drawable.micro_classic_live_forecast_cover);
                    videoPlayer.setThumbImageView(imageView);
                    videoPlayer.hideStatusBtn(false);
                } else {
                    //设置封面图
                    ImageView imageView = new ImageView(this);
                    imageView.setImageResource(R.drawable.micro_classic_live_end_cover);
                    videoPlayer.setThumbImageView(imageView);
                    videoPlayer.hideStatusBtn(false);
                }
            } else {
                videoPlayer.setMode(QYVideoPlayer.PlayMode.NORMAL);
                if (isAuto) {
                    videoPlayer.getStartButton().performClick();//自动播放
                }
            }


        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (QYVideoPlayer.getPlayMode() == QYVideoPlayer.PlayMode.LIVE) {
            if (videoPlayer.isIfCurrentIsFullscreen()) {
                videoPlayer.getStartButton().performClick();
            } else {
                videoPlayer.startPlayLogic();
            }
        } else {
            videoPlayer.onVideoResume();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        videoPlayer.onVideoPause();
    }

    @Override
    public void onBackPressed() {
        if (GSYVideoManager.backFromWindowFull(this)) {
            return;
        }
        super.onBackPressed();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        videoPlayer.release();
        BusFactory.getBus().unregister(this);
    }


    class Adapter extends FragmentPagerAdapter {
        private List<Fragment> fragmentList;
        private List<String> names;

        Adapter(FragmentManager fm, List<Fragment> fragmentList, List<String> names) {
            super(fm);
            this.fragmentList = fragmentList;
            this.names = names;
        }

        @Override
        public Fragment getItem(int position) {
            return fragmentList.get(position);
        }

        @Override
        public int getCount() {
            return fragmentList.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return names.get(position);
        }
    }
}
